﻿using ICMS.PluginInterfaces;
using commonImportPlugin.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using commonImportPlugin.Config;
using commonImportPlugin.Configs.TrackFile;

namespace commonImportPlugin.FilesCore.TrackFile
{
    public class TrackBase : CommonUtil
    {
     
        /// <summary>
        /// 获取每个磁条文件的数据（根据分割符来截取）
        /// </summary>
        /// <param name="allTrackIcDatas">存放所有磁条数据的list</param>
        /// <param name="trackFilePath">一个磁条文件</param>
        /// <param name="config">配置文件</param>
        /// <returns></returns>
        public bool getFileTrackDatas(List<ICData> allTrackIcDatas, string trackFilePath,TrackFileConfig config)
        {
            string[] originTrackLines = null;//所有初始磁条数据
            string track1Data=null;//1磁道数据  
            string track2Data=null;//2磁道数据 
            string track3Data=null;//3磁道数据 

            ICData trackIcData = null;

            if (!File.Exists(trackFilePath))
                throw new Exception("磁条文件不存在！");

            try
            {
                originTrackLines = File.ReadAllLines(trackFilePath,ASCIIEncoding.GetEncoding(config.encoding));
                for (int i = config.dataIndex - 1; i < originTrackLines.Length; i++)
                {
                    trackIcData = new ICData();//磁条数据
                    string[] trackDatas = originTrackLines[i].Split(config.dataSeparators, StringSplitOptions.None);
                    #region 获取1.2.3磁道
                    //一磁道
                    if (config.subTrack1!=null)
                    {
                        int column = config.subTrack1[0];//哪列
                        int subStart = config.subTrack1[1];//起始截取位置
                        int subEnd = config.subTrack1[2];//结束截取位置
                        track1Data = SubString(trackDatas[column - 1], subStart, subEnd);
                    }
                    //二磁道
                    if (config.subTrack2.Length!=null)
                    {
                        int column = config.subTrack2[0];//哪列
                        int subStart = config.subTrack2[1];//起始截取位置
                        int subEnd = config.subTrack2[2];//结束截取位置
                        track2Data = SubString(trackDatas[column - 1], subStart, subEnd);
                    }
                    //三磁道
                    if (config.subTrack3.Length !=null)
                    {
                        int column = config.subTrack3[0];//哪列
                        int subStart = config.subTrack3[1];//起始截取位置
                        int subEnd = config.subTrack3[2];//结束截取位置
                        track3Data = SubString(trackDatas[column - 1], subStart, subEnd);
                    }
                    trackIcData.Track1 = string.Format("%{0}?;{1}?_;{2}?", track1Data, track2Data, track3Data);//拼成指定格式
                    #endregion

                    if (config.subBankCardId != null)//银行卡号
                    {
                        int column = config.subBankCardId[0];
                        int subStart = config.subBankCardId[1];
                        int subEnd = config.subBankCardId[2];
                        trackIcData.BankCardID = SubString(trackDatas[column - 1].Trim(), subStart, subEnd);
                    }
                    if (config.subPersonId != null)//身份证号
                    {
                        int column = config.subPersonId[0];
                        int subStart = config.subPersonId[1];
                        int subEnd = config.subPersonId[2];
                        trackIcData.PersonID = SubString(trackDatas[column - 1].Trim(), subStart, subEnd);
                    }
                    //检查格式
                    if (!string.IsNullOrEmpty(config.dataCheckRegex))
                        TrackDataCheck(trackIcData.Track1, config.dataCheckRegex);

                    allTrackIcDatas.Add(trackIcData);
                }
            }
            catch (Exception e)
            {      
                throw new Exception(e.Message);
            }
            return true;
        }
        
        /// <summary>
        /// 获取每个磁条文件的数据（根据正则匹配来截取）
        /// </summary>
        /// <param name="allTrackIcDatas">存放所有磁条数据的list</param>
        /// <param name="trackFilePath">一个磁条文件</param>
        /// <param name="config">配置文件</param>
        /// <returns></returns>
        public bool getFileTrackDatas(List<ICData> allTrackIcDatas, string trackFilePath, TrackFileConfigRegex config)
        {
            string[] originTrackLines = null;//所有初始磁条数据
            string track1Data = null;//1磁道数据  
            string track2Data = null;//2磁道数据 
            string track3Data = null;//3磁道数据 

            ICData trackIcData = null;

            if (!File.Exists(trackFilePath))
                throw new Exception("磁条文件不存在！");

            try
            {
                originTrackLines = File.ReadAllLines(trackFilePath, ASCIIEncoding.GetEncoding(config.encoding));
                for (int i = config.dataIndex - 1; i < originTrackLines.Length; i++)
                {
                    trackIcData = new ICData();//磁条数据
                    string originTrackLine = originTrackLines[i];            
                    #region 获取1.2.3磁道
                    //一磁道
                    if (config.subTrack1 != null)
                    {
                        track1Data=subStringWithRegex(config.subTrack1, originTrackLine);                                          
                    }
                    //二磁道
                    if (config.subTrack2!= null)
                    {
                        track2Data = subStringWithRegex(config.subTrack2, originTrackLine); 
                    }
                    //三磁道
                    if (config.subTrack3 != null)
                    {
                        track3Data = subStringWithRegex(config.subTrack3, originTrackLine); 
                    }
                    trackIcData.Track1 = string.Format("%{0}?;{1}?_;{2}?", track1Data, track2Data, track3Data);//拼成指定格式
                    #endregion

                    if (config.subBankCardId != null)//银行卡号
                    {
                        trackIcData.BankCardID = subStringWithRegex(config.subBankCardId, originTrackLine); 
                    }
                    if (config.subPersonId != null)//身份证号
                    {
                        trackIcData.PersonID = subStringWithRegex(config.subPersonId, originTrackLine); 
                    }
                    //检查格式
                    if (!string.IsNullOrEmpty(config.dataCheckRegex))
                        TrackDataCheck(trackIcData.Track1, config.dataCheckRegex);

                    allTrackIcDatas.Add(trackIcData);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return true;
        }
        private bool TrackDataCheck(string trackData, string TrackDataRegexs)
        {
            Match match = null;
            bool isSucceed = true;
            string errorMessage = null;
            //检查磁条数据
            if (!string.IsNullOrEmpty(TrackDataRegexs))
            {
                if (!string.IsNullOrEmpty(trackData))
                {
                    match = Regex.Match(trackData.Trim(), TrackDataRegexs.Trim());
                    if (!match.Success)
                    {
                        isSucceed = false;
                        errorMessage = "提取的磁条格式不正确";
                    }
                }
                else
                {
                    isSucceed = false;
                    errorMessage = "提取的磁条为空";
                }
            }
            if (!isSucceed)
                throw new Exception(errorMessage);
            return isSucceed;
        }

        /// <summary>
        /// 根据正则表达式截取指定字符串
        /// </summary>
        /// <param name="rule"></param>
        /// <param name="inputString"></param>
        /// <returns></returns>
        private string subStringWithRegex(string[] rule,string inputString)
        {
            string finalResult = "";
            //检查参数
            string checkError=checkOutInput(rule);
            if(!string.IsNullOrEmpty(checkError))
                throw new Exception(checkError);

            Match match = Regex.Match(inputString, rule[0]);
            if (match.Success)
            {
                int subStart = int.Parse(rule[1]);//起始截取位置
                int subEnd = int.Parse(rule[2]);//结束截取位置
                finalResult = SubString(match.Value, subStart, subEnd).Trim();
            }
            return finalResult;
        }
        /// <summary>
        /// 检查判断输入的规则是否正确
        /// </summary>
        /// <param name="rule"></param>
        /// <returns></returns>
        private string checkOutInput(string[] rule)
        {
            if (rule.Length != 3)
                return string.Format("配置获取磁条的数据参数设置个数有误！");
            if ((!Regex.Match(rule[1], @"\d{1,}").Success) || (!Regex.Match(rule[2], @"\d{1,}").Success))
                return string.Format("配置获取磁条的数据参数设置类型有误！");
            return "";
        }
    }
}
